package cn.firecode.data_collect.controller;
import java.io.*;
import cn.firecode.data_collect.domain.entity.CollectDataT;
import cn.firecode.data_collect.exception.DcsException;
import cn.firecode.data_collect.service.CollectDataTService;
import cn.firecode.data_collect.utils.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yangfan
 * @since 2019-12-10
 */
@RestController
@RequestMapping("/collect")
@Slf4j
public class CollectDataTController {

    @Autowired
    private CollectDataTService dataTService;


    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private String redisPort;

    @RequestMapping(value = "/new/{collectType}", method = RequestMethod.POST)
    public DataResponse add(Integer environmentId, Integer objectId, @PathVariable("collectType")Integer collectType, Integer currentuser){
        CollectDataT dataT = new CollectDataT();
        dataT.setEnvironmentId(environmentId);
        dataT.setObjectId(objectId);
        try{
            dataTService.createDataToRedis(currentuser,dataT);
            dataTService.storeCollectTypeToRedis(currentuser,collectType);
        }catch (DcsException e){
            return DataResponse.failed(1,"业务逻辑错误:"+e.getMessage());
        }

        dataT = dataTService.getDataFromRedis(currentuser);
        Map<String,String> result_temp = new HashMap<>();
        result_temp.put("redisServer",redisHost+":"+redisPort);
        result_temp.put("channel",String.valueOf(dataT.getDataId()));
        return DataResponse.succeed("新增成功",result_temp);
    }


    @RequestMapping(value = "/data", method = RequestMethod.POST)
    public DataResponse updateData(String drillingBeforeNdi, String drillingAfterNdi, String drillingRobotJoint,
                                   double initialDepth, double feedSpeed, String text, Integer drillUseCount ,Integer currentuser){

        CollectDataT dataT = new CollectDataT();
        dataT.setBeforeNdi(drillingBeforeNdi);
        dataT.setDrillPunchCount(drillUseCount);
        dataT.setAfterNdi(drillingAfterNdi);
        dataT.setFeedSpeed(feedSpeed);
        dataT.setHeightOffset(initialDepth);
        dataT.setMotorSpeed(0.0);
        dataT.setRobotJoint(drillingRobotJoint);
        dataT.setText(text);

        try {
            dataTService.updateParToRedis(currentuser, dataT);
        }catch (DcsException e){
            return DataResponse.failed(1,"业务逻辑错误:"+e.getMessage());
        }

        dataT = dataTService.getDataFromRedis(currentuser);
        return DataResponse.succeed("数据更新成功",dataT);

    }


    @RequestMapping(value = "/file/{fileType}/{fileMD5}" , method = RequestMethod.POST)
    public DataResponse updateFile(@PathVariable("fileType") String fileType,
                                   @PathVariable("fileMD5") String fileMD5,
                                   @RequestParam("file") MultipartFile file, Integer currentuser){
        try {
            boolean chechResult = dataTService.chechFileMD5(file.getInputStream(), fileMD5);
            if(!chechResult){
                return DataResponse.failed(2,"文件MD5校验失败");
            }
            dataTService.storeRemoteFile(file.getInputStream(), DcsFileEnum.getEnum(fileType),currentuser,
                    FilenameUtils.getExtension(file.getOriginalFilename()));
            CollectDataT dataT = dataTService.getDataFromRedis(currentuser);
            return DataResponse.succeed("文件上传成功",dataT);
        } catch (IOException e) {
            return DataResponse.failed(3,"文件传输错误");
        }
    }




    @RequestMapping(value = "/done", method = RequestMethod.POST)
    public DataResponse done(Integer currentuser){

        try {
            dataTService.createLineChartForForceZ(currentuser);
            dataTService.checkDataIsIntact(currentuser);
            CollectDataT dataT = dataTService.getDataFromRedis(currentuser);
            dataT.setDataId(null);
            dataT.setStatus(1);
            dataT.setCreateTime(LocalDate.now());
            int rows = dataTService.insertAndGetId(dataT);
            if(rows<0){
                return DataResponse.failed(1,"业务逻辑错误:数据存入数据库失败");
            }
            dataTService.deleteDataFormRedis(currentuser);
            dataTService.deleteCollectTypeFormRedis(currentuser);
            dataTService.deleteLocalCacheFile(currentuser);
            return DataResponse.succeed("数据保存成功",dataT);
        }catch (DcsException e){
            return DataResponse.failed(1,"业务逻辑错误:"+e.getMessage());
        }

    }

    @RequestMapping(value = "/test/create/{count}",method = RequestMethod.GET)
    public DataResponse createDataToRedis(@PathVariable("count")Integer count){
        long start = System.currentTimeMillis();
        dataTService.createDataToRedis(count);
        long end = System.currentTimeMillis();
        return DataResponse.succeed("create succeed used time:"+(end-start)+"ms");
    }


    @RequestMapping(value = "/destroy",method = RequestMethod.GET)
    public DataResponse destroy(Integer currentuser){
       try{
           dataTService.destroyCacheFileFastDfs(currentuser);
           dataTService.deleteLocalCacheFile(currentuser);
           dataTService.deleteCollectTypeFormRedis(currentuser);
           dataTService.deleteDataFormRedis(currentuser);
           return DataResponse.succeed("数据销毁成功","");
       }catch (DcsException e){
           return DataResponse.failed(1,"业务逻辑错误:"+e.getMessage());
       }
    }


    @RequestMapping(value = "/getList",method = RequestMethod.GET)
    public DataResponse getList(){
        QueryWrapper<CollectDataT> wrapper = new QueryWrapper<>();
        wrapper.ne("status",2).orderByAsc("create_time");
        List<CollectDataT> list = dataTService.list(wrapper);
        return DataResponse.succeed(String.valueOf(list.size()),list);
    }
}
